// sale_coin_page.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sjx/pages/mine/coin/sale_coin_page_vm.dart';
import 'package:sjx/pages/mine/coin/sale_coin_success_page.dart';

class SaleCoinPage extends StatefulWidget {
  const SaleCoinPage({Key? key}) : super(key: key);

  @override
  State<SaleCoinPage> createState() => _SaleCoinPageState();
}

class _SaleCoinPageState extends State<SaleCoinPage> {
  final TextEditingController _textController = TextEditingController();
  late SaleCoinViewModel _viewModel;

  @override
  void initState() {
    super.initState();
    _viewModel = SaleCoinViewModel();
    _viewModel.setOnCoinAmountChanged(_updateTextController);
    _loadData();
  }

  // 更新文本控制器的方法
  void _updateTextController() {
    if (_viewModel.coinAmount > 0) {
      _textController.text = _viewModel.coinAmount.toString();
    } else {
      _textController.text = '';
    }
    // 确保光标在文本末尾
    _textController.selection = TextSelection.fromPosition(
      TextPosition(offset: _textController.text.length),
    );
  }


  void _loadData() {
    _viewModel.loadCoinInfo().then((_) {
      if (_viewModel.hasError) {
        _showErrorSnackBar(_viewModel.errorMessage);
      }
    });
  }

  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
      ),
    );
  }

  void _showSuccessSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: _viewModel,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('出售'),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ),
        body: Consumer<SaleCoinViewModel>(
          builder: (context, viewModel, child) {
            if (viewModel.isLoading && viewModel.saleCoinInfo == null) {
              return const Center(
                child: CircularProgressIndicator(),
              );
            }

            return _buildContent(viewModel);
          },
        ),
      ),
    );
  }

  Widget _buildContent(SaleCoinViewModel viewModel) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        children: [
          _buildAvailableCoinsCard(viewModel),
          const SizedBox(height: 16),
          _buildSaleInputCard(viewModel),
          const SizedBox(height: 24),
          _buildSubmitButton(viewModel),
        ],
      ),
    );
  }

  Widget _buildAvailableCoinsCard(SaleCoinViewModel viewModel) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '可出售金币(个)',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey,
              ),
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                Expanded(
                  child: Text(
                    viewModel.availableCoins.toString(),
                    style: const TextStyle(
                      fontSize: 25,
                      color: Color(0xFF2D2D2D),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                TextButton(
                  onPressed: viewModel.sellAll,
                  style: TextButton.styleFrom(
                    foregroundColor: const Color(0xFFFF4974),
                  ),
                  child: const Text('全部出售'),
                ),
              ],
            ),
            const Divider(height: 1),
          ],
        ),
      ),
    );
  }

  Widget _buildSaleInputCard(SaleCoinViewModel viewModel) {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '输入出售个数',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey,
              ),
            ),
            const SizedBox(height: 8),
            TextField(
              controller: _textController,
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: '输入出售个数',
                hintStyle: const TextStyle(
                  fontSize: 25,
                  color: Colors.grey,
                ),
              ),
              style: const TextStyle(
                fontSize: 25,
                color: Color(0xFF2D2D2D),
              ),
              onChanged: (value) {
                final error = viewModel.validateInput(value);
                if (error == null) {
                  viewModel.setCoinAmount(int.parse(value));
                } else {
                  _showErrorSnackBar(error);
                  // 清除无效输入
                  if (value.isNotEmpty) {
                    _textController.text = '';
                    viewModel.setCoinAmount(0);
                  }
                }
              },
            ),
            const Divider(height: 1),
            const SizedBox(height: 16),
            _buildExpectedAmount(viewModel),
          ],
        ),
      ),
    );
  }

  Widget _buildExpectedAmount(SaleCoinViewModel viewModel) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '预计售得金额(元)',
          style: TextStyle(
            fontSize: 13,
            color: Colors.grey,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          viewModel.coinAmount == 0
              ? '1个金币=${viewModel.rate.toStringAsFixed(2)}元'
              : '${viewModel.coinAmount}个金币=${viewModel.expectedAmount.toStringAsFixed(2)}元',
          style: const TextStyle(
            fontSize: 13,
            color: Colors.grey,
          ),
        ),
      ],
    );
  }

  Widget _buildSubmitButton(SaleCoinViewModel viewModel) {
    return SizedBox(
      width: double.infinity,
      height: 44,
      child: ElevatedButton(
        onPressed: viewModel.canSubmit && !viewModel.isLoading
            ? () => _handleSubmit(viewModel)
            : null,
        style: ElevatedButton.styleFrom(
          backgroundColor: const Color(0xFFFF4974),
          disabledBackgroundColor: Colors.grey,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5),
          ),
        ),
        child: viewModel.isLoading
            ? const SizedBox(
          width: 20,
          height: 20,
          child: CircularProgressIndicator(
            strokeWidth: 2,
            valueColor: AlwaysStoppedAnimation(Colors.white),
          ),
        )
            : const Text(
          '确认出售',
          style: TextStyle(
            fontSize: 15,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  Future<void> _handleSubmit(SaleCoinViewModel viewModel) async {
    final success = await viewModel.submitSale();

    if (success) {
      // 跳转到成功页面
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => SaleCoinSuccessPage(
            onComplete: () {
              // 返回到首页或指定页面
              Navigator.popUntil(context, (route) => route.isFirst);
            },
          ),
        ),
      );
    } else {
      _showErrorSnackBar(viewModel.errorMessage);
    }
  }

  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }
}